package com.lucy.common.controller;

import com.lucy.common.domain.ResponseDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author kindear
 */
@Slf4j
@RestController
@RequestMapping("jpa")
@Api(tags = "JPA")
public class JpaController {

    @PersistenceUnit
    EntityManagerFactory entityManagerFactory;

    @GetMapping("tables")
    @ApiOperation(value = "获取所有表",notes = "")
    public ResponseDTO<Object> allTables(){
        List<String> tables = new ArrayList<>();
        SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
        Session session = sessionFactory.openSession();
        if (session != null) {
            tables = session.doReturningWork(
                    connection -> {
                        List<String> resultList = new ArrayList<>();
                        ResultSet rs;
                        String username=connection.getMetaData().getUserName();
                        try {
                            rs = connection.getMetaData().getTables(connection.getCatalog(),username, null, null);
                            while (rs.next()) {
                                String table = rs.getObject(3).toString();
                                resultList.add(table);
                            }
                        } catch (SQLException e) {
                            //不存在
                            return resultList;
                        }
                        rs.close();
                        return resultList;
                    }
            );
            session.close();
        }
        return ResponseDTO.succData(tables);
    }
}
